package hello7;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpClientTest {
	private Socket  socket;
	private OutputStream outS;
	public void connect(String ip,int port)
	{
		socket = new Socket();
		try {
			socket.connect(new InetSocketAddress(InetAddress.getByName(ip), port));
			outS = socket.getOutputStream();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	public void send(String msg)
	{
		try {
			outS.write(msg.getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void read(final MessageListener listener)
	{
		InputStream in = null;
		try {
			in = socket.getInputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		final InputStream in_cp =in;
		Thread t = new Thread(new Runnable(){

			public void run() {
				// TODO Auto-generated method stub

				while(true){
					int len = 0;
			        byte[] data=new byte[1024];
			        try {
						len=in_cp.read(data);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			        if(len>0){
			        	listener.onMessage(new String(data));
			        }
				}
			}
			
		});
		t.start();
	}
	
	
}
